package com.yumo.kangchenjunga.user;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;

import com.yumo.kangchenjunga.company.CompanyEntity;
import com.yumo.kangchenjunga.company.StoreEntity;

@Entity
@Table(name = "user")
public class User {

	@Column(name = "user_id", updatable = false)
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private int id;
	public String username;
	public String password;
	@OneToOne
	@JoinColumn(name = "company_id")
	public CompanyEntity company;
	@OneToOne
	@JoinColumn(name = "store_id", nullable = true)
	public StoreEntity store;
	public String salt = UUID.randomUUID().toString();
	public String privilege;

	public User() {
		// Empty.
	}

	public User(UserVo vo, CompanyEntity company, StoreEntity store) {
		this.id = vo.id;
		this.username = vo.username;
		this.password = DigestUtils.sha256Hex(salt + vo.password);
		this.company = company;
		this.store = store;
		this.privilege = vo.privilege;
	}

	public int getId() {
		return id;
	}

	public static User create(UserRepository repository, User user) {
		user.id = 0;
		return repository.save(user);
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public boolean verifyPassword(String password) {
		return StringUtils.equals(DigestUtils.sha256Hex(salt + password), this.password);
	}

	public void changePassword(String newPassword) {
		salt = UUID.randomUUID().toString();
		password = DigestUtils.sha256Hex(salt + newPassword);
	}

}
